import tokenCenter from '../../utils/token';
import type { RequestPayload, ApiProxy } from './types';
import { RequestResultError, authError } from './result';
import userModel from '../../models/user';

export async function requestWrapper<T = any>(payload: RequestPayload, proxy: ApiProxy<T>) {
  if (!payload.skipToken) {
    if (!payload.token) {
      payload.token = await tokenCenter.getToken();
    }
  }
  try {
    const result = await proxy(payload);
    return result;
  } catch (err) {
    if (err instanceof RequestResultError) {
      if (err.code === authError.code) {
        userModel.getState().logout();
      }
    }
    return Promise.reject(err);
  }
}


